package com;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    //定义变量 接收 driverclass对象  指定数据库路径 用户名 密码
    private static String DriverClass;
    private static String URL;
    private static String UserName;
    private static String PassWord;


    static {
        //通过类加载器 获取属性集 的信息
        InputStream IS = JDBCUtils.class.getClassLoader().getResourceAsStream("D:\\idea_Code\\day05_JDBC\\src\\jdbc.properties");
        //创建一个属性集接收 并以 复制给 变量
        Properties pro = new Properties();
        try {
            pro.load(IS);
            String DriverClass = pro.getProperty("DriverClass");
            String URL=pro.getProperty("URL");
            String UserName=pro.getProperty("UserName");
            String PassWord=pro.getProperty("PassWord");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //反射注册驱动 只注册一次
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //定义一个获取Connection对象静态方法
    public static  Connection  getConnection() throws ClassNotFoundException, SQLException {
        Connection connection = DriverManager.getConnection(URL, UserName, PassWord);//获取连接对象
        return connection;
    }
    //定义一个释放资源方法
    public static void  Close(Connection conn,Statement stm,ResultSet rs){
        if(null !=conn){
            try {
                conn.close();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }
        if(null !=stm){
            try {
                stm.close();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }
        if(null !=rs) {
            try {
                rs.close();
            } catch (SQLException exception) {
                exception.printStackTrace();
            }
        }
    }
}
